<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\cache\brand\BrandAliasCache;
use Biz\model\brand\Brand as mBrand;
use Biz\model\brand\BrandInfoAudit as mBrandInfoAudit;
use Biz\model\brand\BrandInfoAuditLog as mBrandInfoAuditLog;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\model\brandIndex\BrandMsg as mBrandMsg;
use Biz\service\BrandIndex as sBrandIndex;
use Doraemon\cache\Queue;
use Doraemon\service\User as sUser;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

/**
 * 品牌基础信息审核
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */
class BaseInfoAuditController extends Controller
{
    // 品牌身份
    const BRAND_TYPE = [
        0 => '待定',
        1 => '到期品牌',
        2 => '认证品牌',
        3 => '精选品牌',
        4 => '超级品牌',
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $params = $request->all();
        unset($params['_pjax']);

        $page_size = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $condition = [];
        if (!empty($params['brand_id'])) {
            $condition['brand_id'] = $params['brand_id'];
        }

        if (!empty($params['brand_name'])) {
            $condition['brand_name'] = $params['brand_name'];
        }

        if (!empty($params['audit_status']) || $params['audit_status'] == '0') {
            $condition['audit_status'] = $params['audit_status'];
        }

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $lists = mBrandInfoAudit::select('*', $condition);

        unset($condition['ORDER']);
        unset($condition['LIMIT']);
        $total = mBrandInfoAudit::count('*', $condition);

        return $content
            ->header('品牌基础信息审核')
            ->breadcrumb(
                ['text' => '品牌基础信息审核', 'url' => '/baseInfo/audit']
            )
            ->body($this->grid($lists, $total, $page_size));
    }

    private function grid($lists, $total, $page_size)
    {
        if (!empty($lists)) {
            $brand_ids = array_column($lists, 'brand_id');

            // 品牌账户信息（认证到期时间、入驻到期时间）
            $all_brand_account = BrandAccountInfo::getAllByWhere([
                'brand_id' => $brand_ids,
                'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
                'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
                'uid[!]' => 0
            ]);

            $map_account = [];
            if (!empty($all_brand_account)) {
                foreach ($all_brand_account as $item) {
                    $map_account[$item['brand_id']] = $item;
                }
            }

            foreach ($lists as &$item) {
                $item['brand_type'] = self::BRAND_TYPE[$map_account[$item['brand_id']]['brand_type']];
                $item['letter_time'] = empty($map_account[$item['brand_id']]) ?
                    '-' : $map_account[$item['brand_id']]['letter_time'];
                $item['in_end_time'] = empty($map_account[$item['brand_id']]['in_end_time']) ?
                    '-' : $map_account[$item['brand_id']]['in_end_time'];
                $item['brand_alias'] = empty($item['brand_alias']) ? '' :
                    implode('、', json_decode($item['brand_alias'], true));
            }
            unset($item);
        }

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($attribute) {
            $grid->filter(function (Grid\Filter $filter) use ($attribute) {
                $filter->disableIdFilter();
                $filter->column(1 / 3, function ($filter) use ($attribute) {
                    $filter->equal('brand_id', '品牌id')->placeholder('请输入品牌id');
                });
                $filter->column(1 / 3, function ($filter) use ($attribute) {
                    $filter->equal('brand_name', '品牌名称')->placeholder('请输入品牌名称');
                });
                $filter->column(1 / 3, function ($filter) use ($attribute) {
                    $filter->equal('audit_status', '审核状态')->select([0 => '待审核', 1 => '审核通过', 2 => '审核未通过']);
                });
                $filter->expand();
            });

            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->column('brand_id', '品牌ID')->width(80);
            $grid->column('brand_name', '品牌名称')->width(140);
            $grid->column('brand_alias', '品牌别称')->width(140);
            $grid->column('brand_type', '品牌身份')->width(100);
            $grid->column('letter_time', '认证到期时间')->width(140);
            $grid->column('in_end_time', '入驻到期时间')->width(140);
            $grid->column('audit_status', '审核状态')->display(function () {
                return mBrandInfoAudit::AUDIT_STATUS[$this->audit_status];
            })->width(100);
            $grid->column('admin_id', '处理人')->display(function () {
                if (!$this->admin_id) {
                    return '-';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            })->width(100);

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();

                if (in_array($actions->row->audit_status, [
                    mBrandInfoAudit::AUDIT_STATUS_WAIT, mBrandInfoAudit::AUDIT_STATUS_FAIL])) {
                    $actions->append("<a href=\"/admin/brand/baseInfo/audit/" .
                        $actions->row->id . "\" class=\"btn btn-success\">审核</a>");
                }
            });
        });

        return $listGrid->render();
    }

    public function auditInfo(Content $content, $id)
    {
        $audit_data = mBrandInfoAudit::get('*', ['id' => $id]);
        $brand_id = $audit_data['brand_id'];
        $brand_info = mBrand::getBrandInfoById($brand_id);
        $brand_account = BrandAccountInfo::getOneByWhere([
            'brand_id' => $brand_id,
            'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
        ]);

        $data = [
            'brand_id' => $audit_data['brand_id'],
//            'brand_type' => mBrand::BRAND_TYPE[$brand_info['brand_type']],
            'logo' => $brand_info['logo'] ? $brand_info['logo'] : '96369302802800000ovjdos',
            'letter_time' => $brand_account['letter_time'],
            'in_end_time' => empty($brand_account['in_end_time']) ? '' : $brand_account['in_end_time'],
            'old_brand_name' => $brand_info['brand_name'],
            'new_brand_name' => $audit_data['brand_name'],
            'old_brand_alias' => empty($brand_info['brand_alias']) ? '' :
                implode(' ', json_decode($brand_info['brand_alias'], true)),
            'new_brand_alias' => empty($audit_data['brand_alias']) ? '' :
                implode(' ', json_decode($audit_data['brand_alias'], true)),
            'audit_status' => $audit_data['audit_status']
        ];

        $form = new Form($data);
        $form->hidden('brand_id');
        $form->text('brand_id', '品牌id')->setWidth(4, 2)->readOnly();
//        $form->text('brand_type', '品牌身份')->setWidth(4, 2)->readOnly();
        $form->imgUpload('logo', '品牌logo', false, ['isUpload' => false, 'isGetUrl' => true, 'imgType' => ImgUrl::APPTYPE_BIZ, 'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG])->readOnly();

        $form->text('letter_time', '认证到期时间')->setWidth(4, 2)->readOnly();
        $form->text('in_end_time', '入驻到期时间')->setWidth(4, 2)->readOnly();

        $button = '';
        if ($data['old_brand_name'] != $data['new_brand_name'] ||
            $data['old_brand_alias'] != $data['new_brand_alias']) {
            if ($data['old_brand_name'] != $data['new_brand_name']) {
                $form->text('old_brand_name', '现品牌名称')->setWidth(4, 2)->readOnly();
                $form->text('new_brand_name', '修改后的品牌名称')->setWidth(4, 2)->readOnly();
            }

            if ($data['old_brand_alias'] != $data['new_brand_alias']) {
                $form->text('old_brand_alias', '现品牌别称')->setWidth(4, 2)->readOnly();
                $form->text('new_brand_alias', '修改后的品牌别称')->setWidth(4, 2)->readOnly();
            }
        }

        if ($data['audit_status'] == mBrandInfoAudit::AUDIT_STATUS_WAIT) {
            $button = '<div style="text-align: right"><a href="/admin/brand/baseInfo/audit/' .
                $id . '/pass" class="btn btn-primary" onclick="return confirm(\'确认通过审核吗？\');">审核通过</a>
                    <a href="javascript:layer.open({
                        type: 2,
                        title: \'审核不通过\',
                        maxmin: true,
                        area: [\'800px\', \'500px\'],
                        content: \'/admin/brand/reject/' . $id . '\'
                        });" class="btn btn-primary">审核不通过</a>
                   </div>';
        } elseif ($data['audit_status'] == mBrandInfoAudit::AUDIT_STATUS_FAIL) {
            $button = '<div style="text-align: right"><a href="/admin/brand/baseInfo/audit/' .
                $id . '/pass" class="btn btn-primary" onclick="return confirm(\'确认通过审核？\');">审核通过</a></div>';
        }

        return $content
            ->header('品牌基础信息审核')
            ->breadcrumb(
                ['text' => '品牌基础信息审核', 'url' => '/admin/brand/baseInfo/auditList']
            )->body($button)
            ->row($form->render());
    }

    public function audit(Request $request, Content $content, $id, $op)
    {
        $audit_info = mBrandInfoAudit::get('*', ['id' => $id]);
        $brand_id = $audit_info['brand_id'];

        $brand_info = mBrand::getBrandInfoById($brand_id);

        if ($op == 'pass') {
            $update_data = [
                'audit_status' => mBrandInfoAudit::AUDIT_STATUS_PASS,
                'admin_id' => Admin::user()->id,
            ];
            mBrandInfoAudit::update($update_data, ['id' => $id]);

            // 更新品牌表信息
            $data = [
                'brand_name' => $audit_info['brand_name'],
                'brand_alias' => $audit_info['brand_alias']
            ];
            $result = mBrand::updateBrandInfoById($brand_id, $data);

            // 记录审核前后的数据日志
            $old_data = [
                'brand_name' => $brand_info['brand_name'],
                'brand_alias' => $brand_info['brand_alias']
            ];
            $new_data = [
                'brand_name' => $audit_info['brand_name'],
                'brand_alias' => $audit_info['brand_alias']
            ];
            $data = [
                'old_data' => json_encode($old_data),
                'new_data' => json_encode($new_data),
                'add_time' => time(),
                'admin_id' => Admin::user()->id
            ];
            mBrandInfoAuditLog::insert($data);

            if ($result) {
                if (!empty($audit_info['brand_alias'])) {
                    $new_brand_alias = json_decode($audit_info['brand_alias'], true);
                    foreach ($new_brand_alias as $alias) {
                        BrandAliasCache::setBrandName($alias, $audit_info['brand_name']);
                        BrandAliasCache::addBrandAlias($alias);
                    }
                }

                if (!empty($brand_info['brand_alias'])) {
                    $old_brand_alias = json_decode($brand_info['brand_alias'], true);
                    foreach ($old_brand_alias as $alias) {
                        BrandAliasCache::delBrandAlias($alias);
                    }
                }

                \Doraemon\cache\EsUpdateCollector::multiInsertBrandIdsForWikiBasic([$brand_id]);

                // 审核通过下行通知消息
                $msg = '你提交的品牌名称/别称的修改申请已审核通过，并已生效';
                if (!empty($brand_info['uid'])) {
                    $message = [
                        'msgCode' => 0,
                        'to_uid' => $brand_info['uid'],
                        'msgParams' => [
                            'from_uid' => sUser::DEFAULT_HAOHAOZHU_UID,
                            'title' => '',
                            'detail' => $msg,
                        ],
                    ];
                    Queue::insertQueue('queue/Sysmsg/Send', $message, Queue::QUEUE_DORAEMON);

                    sBrandIndex::writeMsg(
                        $brand_id,
                        mBrandMsg::MSG_TYPE_PASS,
                        mBrandMsg::MSG_SOURCE_BASIC,
                        $msg
                    );
                }

                $success = new MessageBag([
                    'title' => '操作成功'
                ]);

                return back()->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);

                return back()->with(compact('error'));
            }
        }
    }

    public function rejectLayer($id)
    {
        return view('brand::audit.reject', [
            'id' => $id,
        ]);
    }

    public function reject(Request $request)
    {
        $params = $request->all();

        $update_data = [
            'audit_status' => mBrandInfoAudit::AUDIT_STATUS_FAIL,
            'reason' => $params['reason'],
            'admin_id' => Admin::user()->id,
        ];

        $result = mBrandInfoAudit::update($update_data, ['id' => $params['id']]);

        if (empty($result)) {
            return response()->json(['msg' => '操作失败', 'code' => 0]);
        } else {
            $brand_info_audit = mBrandInfoAudit::get('*', ['id' => $params['id']]);
            $brand_info = mBrand::getBrandInfoById($brand_info_audit['brand_id']);

            // 审核不通过下行通知消息
            if (!empty($brand_info['uid'])) {
                $message = [
                    'msgCode' => 0,
                    'to_uid' => $brand_info['uid'],
                    'msgParams' => [
                        'from_uid' => sUser::DEFAULT_HAOHAOZHU_UID,
                        'title' => '',
                        'detail' => $params['reason'],
                    ],
                ];
                Queue::insertQueue('queue/Sysmsg/Send', $message, Queue::QUEUE_DORAEMON);

                sBrandIndex::writeMsg(
                    $brand_info_audit['brand_id'],
                    mBrandMsg::MSG_TYPE_OVER,
                    mBrandMsg::MSG_SOURCE_BASIC,
                    $params['reason']
                );
            }

            return response()->json(['msg' => '操作成功', 'code' => 1]);
        }
    }
}
